package edu.bupt.producerconsumer;

import java.util.LinkedList;
import java.util.Queue;

public class Controller2 {


    private volatile int number = 0;
    static Controller2 resource = new Controller2();
    private Queue<Integer> queue = new LinkedList<Integer>();
    public static void main(String[] args) {
        new Thread(new ProducerThread(resource)).start();
        new Thread(new ConsumerThread(resource)).start();
        new Thread(new ProducerThread(resource)).start();
        new Thread(new ConsumerThread(resource)).start();
        new Thread(new ProducerThread(resource)).start();
        new Thread(new ConsumerThread(resource)).start();
    }

    /**
     * 增加公共资源
     */
    public synchronized void produce() {
        while (queue.size() == 20) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("produce : " + number);
        queue.offer(number);
        number++;
        notify();
    }

    /**
     * 减少公共资源
     */
    public synchronized void consume() {
        while (queue.size() == 0) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("consume: " + queue.poll());
        notify();
    }



    /**
     * 生产者线程，负责生产公共资源
     */
     static class ProducerThread implements Runnable {
        private Controller2 resource;
        public ProducerThread(Controller2 resource) {
            this.resource = resource;
        }
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep((long) (Math.random() * 1000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                resource.produce();
            }
        }
    }
    /**
     * 消费者线程，负责消费公共资源
     */
    static class ConsumerThread implements Runnable {
        private Controller2 resource;
        public ConsumerThread(Controller2 resource) {
            this.resource = resource;
        }
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep((long) (Math.random() * 1000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                resource.consume();
            }
        }
    }
	
}